import { loginApi, getInfoApi } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

// 存一个共用的token
const state = {
  token: getToken(),
  // 用户资料
  userInfo: {}
}

const mutations = {
  setToken(state, data) {
    state.token = data
    setToken(data)
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  // 设置用户资料
  setUserInfo(state, data) {
    state.data = data
  },
  // 删除用户资料
  removeUserInfo() {
    state.userInfo = {}
  }

}

const actions = {
  async loginAction(context, data) {
    const res = await loginApi(data)
    console.log(res)
    context.commit('setToken', res)
  },
  async getUserProfileAction(context) {
    // 发送请求
    const res = await getInfoApi()

    // console.log(res)
    context.commit('setUserInfo', res)
  },
  logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

